#!/usr/bin/env bash
### BEGIN INIT INFO
# Provides:          <NAME>
# Required-Start:    $local_fs $network $named $time $syslog
# Required-Stop:     $local_fs $network $named $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       <DESCRIPTION>
### END INIT INFO

__dir_path="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
__dir_name="$(basename ${__dir_path})"

cd $__dir_path

if [[ ! -f service.conf ]]; then
    echo "config file not found"
    exit 0
else
    source ./service.conf
fi

if [  ! "${ACTIVE_PROFILES}" = "" ]; then
  JVM_OPTS="${JVM_OPTS} -Dspring.profiles.active=${ACTIVE_PROFILES}"
fi

if [ ! "${SERVER_PORT}" = "" ]; then
  JVM_OPTS="${JVM_OPTS} -Dserver.port=${SERVER_PORT}"
fi

if [ "${ENABLE_APR}" = 1 ]; then
  JVM_OPTS="${JVM_OPTS} -Djava.library.path=${NATIVE_PATH} -Dserver.tomcat.apr.enabled=true"
fi

if [ "${ENABLE_PINPOINT}" = 1 ]; then
  TMP_HOSTNAME=`hostname`
  export HOSTNAME=`echo $TMP_HOSTNAME | egrep -o '^[^\.]+'`
  export APP=`echo $TMP_HOSTNAME | egrep -o '^[0-9a-z]*-[0-9a-z]*'`

  JVM_OPTS="$JVM_OPTS -javaagent:/home/webedit/pp/pp-agent/pinpoint-bootstrap-1.6.2.jar"
  JVM_OPTS="$JVM_OPTS -Dpinpoint.agentId=$HOSTNAME"
  JVM_OPTS="$JVM_OPTS -Dpinpoint.applicationName=$APP"
fi

APP_PATH="./${NAME}-${VERSION}.jar"
SCRIPT="${JAVA_CMD} ${JVM_OPTS} -jar ${APP_PATH}"

if [ ! -f ${APP_PATH} ]; then
  echo "${APP_PATH} no found"
  exit 0
fi

PIDFILE="./${NAME}.pid"
LOG_DIR="${LOG_PATH}/${NAME}"

LOGFILE="${LOG_DIR}/${NAME}.log"

start() {
  if [ -f "${PIDFILE}" ] && [ -s "${PIDFILE}" ] && kill -0 $(cat "${PIDFILE}"); then
    echo 'Service already running' >&2
    return 1
  fi
  echo 'Starting service…' >&2
  if [ ! -d "${LOG_DIR}" ]; then
    mkdir ${LOG_DIR}
    echo "Create dir ${LOG_DIR}"
  fi
  nohup  ${SCRIPT} >> "${LOGFILE}" 2>&1 &
  PID=$!
  #echo "Saving PID" $PID " to " $PIDFILE
  if [ -z "$(ps aux | grep ${PID} | grep -v grep)" ]; then
    echo "Error! Could not start Service!"
  else
    echo ${PID} > "${PIDFILE}"
    echo "Service is now running, the PID is ${PID}"
  fi
}

stop() {
  if [ ! -f "${PIDFILE}" ] || ! kill -0 $(cat "${PIDFILE}"); then
    echo 'Service not running' >&2
    return 1
  fi
  echo 'Stopping service…' >&2
  kill -15 $(cat "${PIDFILE}") && rm -f "${PIDFILE}"
  echo 'Service stopped' >&2
}


status() {
    if [ "$2" = "health_check" ]; then
        printf "%-50s" "Checking Service health ..."
        HEALTH_CHECK=1
    else
        printf "%-50s" "Checking Service..."
    fi

    if [ -f "${PIDFILE}" ] && [ -s "${PIDFILE}" ]; then
        PID=$(cat "${PIDFILE}")
            if [ -z "$(ps aux | grep ${PID} | grep -v grep)" ]; then
                printf "%s\n" "The process appears to be dead but pidfile still exists"
                rm -f "${PIDFILE}"
                if [ -n "${HEALTH_CHECK}" ]; then
                    return 1
                fi
            else
                echo "Running, the PID is ${PID}"
            fi
    else
        printf "%s\n" "Service not running"
        if [ -n "${HEALTH_CHECK}" ]; then
            return 1
        fi
    fi
}



logs() {
    if [ -f "${LOGFILE}" ]; then
        printf "%-50s\n" "tail -fn100 ${LOGFILE}"
        echo "--------------"
        tail -fn100 "${LOGFILE}"
    else
        echo "Logfile:${LOGFILE} not exits"
    fi
}


case $1 in
  start)
    start
    ;;
  stop)
    stop
    ;;
  status)
    status $@
    ;;
  restart)
    stop
    start
    ;;
  logs)
    logs
    ;;
  *)
    echo "Usage: $0 {start|stop|status|restart|logs}"
esac
